package server;

import java.io.*;
import java.net.*;
import java.rmi.server.*;
import java.security.KeyStore;
import javax.net.ssl.*;

public class RMISSLClientSocketFactory implements RMIClientSocketFactory, Serializable {

   
	private static final long serialVersionUID = 1L;

	public Socket createSocket(String host, int port) throws IOException
	{
	    SSLSocketFactory sf = null;
	    SSLSocket s = null;

	    try {
    	 	// set up key manager to do server authentication
   	   		SSLContext ctx;
   	   		KeyManagerFactory kmf;
			TrustManagerFactory tmf;
   	   		KeyStore ks, ts;
	    	char[] passphrase = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();;
   		    char[] keypassphrase = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
   	   		
   		    ctx = SSLContext.getInstance("TLS");
	      	kmf = KeyManagerFactory.getInstance("SunX509");
            tmf = TrustManagerFactory.getInstance("SunX509");
	      	ks = KeyStore.getInstance("JKS");
	      	ts = KeyStore.getInstance("JKS");

	      	ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), passphrase);
	      	ts.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), keypassphrase);
	      	kmf.init(ks, passphrase);
	      	tmf.init(ts);
   	   		ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

	      	sf = ctx.getSocketFactory();
	    } catch (Exception e) {
	      	e.printStackTrace();
	    }
	    s = (SSLSocket)sf.createSocket(host, port);
	    return s;
	}
}
